package com.lin.missyou.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lin.missyou.exception.http.ServerErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.persistence.AttributeConverter;
import javax.persistence.Convert;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * List与JSON之间相互转换
 * @author gcq
 * @Create 2021-10-17
 */
@Convert
public class ListAndJson implements AttributeConverter<List<Object>, String> {

    /**
     * SpringBoot内置json转换 jackson
     */
    @Autowired
    ObjectMapper mapper;

    /**
     * 将list转换成json
     * @param attribute
     * @return
     */
    @Override
    public String convertToDatabaseColumn(List<Object> attribute) {
        try {
            return mapper.writeValueAsString(attribute);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new ServerErrorException(9999);
        }
    }

    /**
     * 将json转换成List
     * @param s
     * @return
     */
    @Override
    public List<Object> convertToEntityAttribute(String s) {
        try {
            if(s == null){
                return null;
            }
            return mapper.readValue(s, List.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new ServerErrorException(9999);
        }
    }


}